package mysql

import (
	"douyin/models"
	"douyin/utils/pkg/snowflake"

	"go.uber.org/zap"
)

// InsertVid 插入视频数据
func InsertVid(vid *models.Vid) (err error) {
	//1.生成videoId
	videoId := snowflake.GenID()
	vid.Id = videoId
	//2.插入数据库
	tx := db.Debug().Model(&models.Vid{}).Create(vid)
	if tx.Error != nil {
		return tx.Error
	}
	return
}

// InsertPublisher 插入视频发布者的数据
func InsertPublisher(pub *models.Publisher) (err error) {
	tx := db.Debug().Model(&models.Publisher{}).Select("UserId", "VideoId").Create(pub)
	if tx.Error != nil {
		return tx.Error
	}
	return
}

// SelectPublisher 通过userId查询用户发布视频id列表
func SelectPublisher(userId int64) (vidIds []int64, err error) {
	//select VideoId from Publisher where UserId =1 ORDER BY CreateTime DESC
	tx := db.Debug().Model(&models.Publisher{}).Select("video_id").Where("user_id=?", userId).Order("create_time DESC").Find(&vidIds)
	//找不到记录，报错
	if len(vidIds) == 0 {
		return nil, ErrorQueryZeroRecord
	}
	//未知错误
	if tx.Error != nil {
		return nil, tx.Error
	}
	return
}

// SelectVideos 根据vidIds批量查询视频，此处userId为登录用户
func SelectVideos(vidIds []int64, userId int64) (videoList []models.Video, err error) {
	//1.通过vidIds查询vidList
	var vidList = make([]models.Vid, 10)
	tx := db.Debug().Model(&models.Vid{}).Where("video_id", vidIds).Find(&vidList)
	if tx.Error != nil {
		return nil, tx.Error
	}
	//2.组合构建 videoList
	for _, v := range vidList {
		user, _ := SelectPublisherByVidId(v.Id)
		//查询用户关系；点赞情况
		if userId != 0 {
			follow := WhetherFollow(userId, user.Id)
			isLike := WhetherVideoLike(v.Id, userId)
			user.IsFollow = follow
			v.IsFavorite = isLike
		}
		temp := models.Video{
			Id:            v.Id,
			Author:        user, //用户组合
			PlayUrl:       v.PlayUrl,
			CoverUrl:      v.CoverUrl, //是否登录都应该能看到默认封面
			FavoriteCount: v.FavoriteCount,
			CommentCount:  v.CommentCount,
			IsFavorite:    v.IsFavorite,
			Title:         v.Title,
		}
		videoList = append(videoList, temp)
	}
	return
}

// SelectPublisherByVidId 通过视频ID查找到用户
func SelectPublisherByVidId(vidId int64) (user models.User, err error) {
	//1. 查用户Id
	var userId int64
	tx := db.Debug().Model(&models.Publisher{}).Select("user_id").Where("video_id = ?", vidId).Find(&userId)
	if userId == 0 {
		err = ErrorQueryZeroRecord
		return
	}
	if tx.Error != nil {
		err = ErrorQueryFailed
		return
	}
	//2. 查找用户
	user, err = SelectUserByUserId(userId)
	if err != nil {
		zap.L().Error("mysql.SelectPublisherByVidId failed", zap.Error(err))
		return
	}
	return
}

// SelectUserByUserId 通过用户Id查找用户
func SelectUserByUserId(userId int64) (user models.User, err error) {
	tx := db.Debug().Model(&models.User{}).Where("user_id=?", userId).Find(&user)
	//找不到记录，报错
	if user.Id == 0 {
		err = ErrorQueryZeroRecord
		return
	}
	if tx.Error != nil {
		err = ErrorQueryFailed
		return
	}
	return
}
